JavaScript数组中推送和赋值之间的区别


async getModifiedData() {
let dbData = await dbdata.getData();

let fileData = [];
dbData.map(data => {
fileData[data["uniquePropertyName"]] = data;
});
return fileData; // here I'm getting empty array
}

而我在使用push()方法时得到了填充数组,

async getModifiedData() {
let dbData = await dbdata.getData();

let fileData = [];
dbData.map(data => {
let propertyName = data["uniquePropertyName"];
let obj = {};
obj[propertyName] = data;
fileData.push(obj);
});
return fileData; // here I'm getting filled array
}

当数组大小较小时,两者都正常工作,但对于较大的数组,Array.push()只返回填充数组。有人能解释一下这里发生了什么吗。

您可以为数组或和对象分配一些东西,但执行方式不同。如果你给数组赋值,你应该使用索引(尽管@tehhowch的答案是正确的,但我们从来没有像给对象赋值那样给数组赋值(。如果要为对象分配一些内容,则应该使用键值(通常是字符串,但并不总是字符串(。

此外,正如其他人所提到的,.map在对另一个数组中的每个元素执行某些操作后返回一个新数组。映射需要返回一个值。forEach只是编写for循环的一种较短的方法;它将遍历数组(或任何可迭代对象(中的每个值并执行某些操作,但它不要求返回某些内容,并且不能返回的内容。

.push只是将一些东西推入一个数组(进入末尾,而不是开头(

为了清楚起见,下面的示例。

//.map
const example = [1, 2, 3, 4];
const exampleDoubled = example.map(number => {
return number * 2;
});
console.log(exampleDoubled);
//expected output: [2, 4, 6, 8]
//.forEach
example.forEach(number => {
//for each number, do something
console.log(number);
// no return value needed
});
//expected output:
//1
//2
//3
//4
//Assigning to an array
const newArray = Array(3);
newArray[0] = 1;
newArray[1] = 2;
newArray[2] = 3;
console.log(newArray);
//expected output: [1, 2, 3]
//Notice that we're assigning using indexes because we're dealing with an array

//Assigning to an object
const newObject = {};
newObject['anyKey'] = "any value. does not have to be a string";
newObject['someOtherKey'] = function() { //do stuff };
console.log(newObject);
//expected output:
// {
// 'anyKey': "any value. does not have to be a string",
// 'someOtherKey': [Function]
//}
//.push
const myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray);
//expected output: [1, 2, 3, 4]

我猜你想要的代码是什么(我不知道数据是什么样子的,所以我不能给你一个确切的答案(;

async getModifiedData() {
let dbData = await dbdata.getData();

let fileData = dbData.map(data => {
return data["uniquePropertyName"];
//assuming here that data is an object and you want an array
//of a particular value from these objects
});
return fileData;
}

希望这能有所帮助!有关详细信息,您可以随时查看MDN和W3Schools文档。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Maphttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEachhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

为了简化,代码中有几个不同的问题,但我将重点讨论为什么第一个示例没有实际填充数组:

在JavaScript中,您可以使用方括号中的数字索引直接将值分配给数组槽,从而将值放入数组中,即使该索引以前没有使用过:

var a = [];
a[2] = 'foo';
console.log(a.length); // => 3

您也可以通过使用方括号中的字段名称直接分配给对象字段来将值放入对象字段:

var a = {};
a['foo'] = 'bar';

正如您所看到的,语法是相同的。此外,您必须记住,在Javascript中,一切都是一个对象,包括数组。通过理解名称为数字的字段会影响数组长度和迭代内容,可以说数组是专门化的对象。

因此,您的第一个示例实际上并没有将fileData作为一个数组来处理——它将其视为一个对象,该对象恰好初始化为一个空数组。设置所有附加的非数字字段后,数组仍然为空。(这是假设uniquePropertyName字段包含文本而不是数字——如果它有时确实包含数字,那么这将解释为什么"有时它有效"(。

最新更新