সিম্পল for লুপ এবং break ব্যবহার করে অ্যারের প্রথম এলিমেন্ট বের করা যায়। অ্যারে খালি কিনা চেক করুন।
উদাহরণ
var studentDetails = [
{ "firstName": "John" },
{ "firstName": "David" },
{ "firstName": "Bob" },
{ "firstName": "Mike" },
{ "firstName": "Carol" }
];
var firstObjectValue = "";
if (studentDetails.length > 1) {
for (var index = 0; index < studentDetails.length; index++) {
firstObjectValue = studentDetails[index].firstName;
break;
}
} else {
firstObjectValue = undefined;
}
if (firstObjectValue != undefined)
console.log(firstObjectValue);
else
console.log("There is no element in the array");
কমান্ড: node fileName.js
আউটপুট
PS C:\Users\Amit\javascript-code> node demo184.js John