Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วนลูปตัวเลขกับค่าออบเจกต์และ push ผลลัพธ์ลงอาร์เรย์ - JavaScript

สมมติว่าต่อไปนี้คือตัวเลขของเราที่มีค่าออบเจกต์:

var numberObject = { 2: 90, 6: 98 }

ใช้ Array.from() ใน JavaScript:

var fillThePositionValue = Array.from({length: 15}, (value, index) => numberObject[index + 1] || "novalue")

ตัวอย่าง

var numberObject = { 2: 90, 6: 98 }
console.log("The actual object is=");
console.log(numberObject);
var fillThePositionValue = Array.from({length: 15}, (value, index) => numberObject[index + 1] || "novalue")
console.log("After filling the value, the actual object is=");
console.log(fillThePositionValue)

เพื่อรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้:

node fileName.js.

ที่นี่ ชื่อไฟล์ของฉันคือ demo215.js

ผลลัพธ์

ผลลัพธ์มีดังนี้:

PS C:\Users\Amit\JavaScript-code> node demo215.js
The actual object is= { '2': 90, '6': 98 }
After filling the value, the actual object is= [
  'novalue', 90, 'novalue', 'novalue', 'novalue', 98, 'novalue', 'novalue', 'novalue', 'novalue', 'novalue', 'novalue', 'novalue', 'novalue', 'novalue'
]