[英]Is there another way pushing data to array in js
這是我的代碼將數據推送到數組變量,但我得到了一個空白數組。 我究竟做錯了什么?
let users = []
//looping ajax response here
for(var i = 0; i < response.length; i++ ) {
users.push(response[i].user_name)
}
當我運行 console.log 這就是我得到的
console.log(users) // Array[]
您也可以使用 Javascript Array 的map
函數,如下所示,但在此之前,您需要確保響應具有數組類型的數據。
首先,我們檢查響應不是未定義的,然后我們從響應循環,如果響應有數據。
//looping ajax response here
let users = response && response.map(x => {
return x.user_name;
});
似乎您缺少i
變量值作為響應。
var response=[{user_name:'abc'},{user_name:'def'}]
let users = [];
for(var i = 0; i < response.length; i++ ) {
users.push(response[i].user_name)
}
使用此代碼后,您應該在用戶數組中獲得結果。
是的,您可以輕松地向現有數組添加新值,而無需使用 push() 方法,只需使用 ES6+ 功能進行數組解構即可。
這是代碼! 非常簡單和需要
var numberArray = []; for (let index = 0; index < 10; index++) { numberArray = [...numberArray, index * 10]; // destructring the old array and adding new element } console.log(numberArray); // update array
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.