我试过谷歌搜索这个问题并搜索了stackoverflow,但没有成功,所以作为最后的手段,我要求以防万一有人能指出我正确的方向。
我举了一个例子,说明我的代码如下所示。
var objectInfo = [
{
name:"object1",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}],
}, {
name:"object2",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}, {
name: "bricks",
quantity:100
}],
}]
我的问题是,如何获得材质对象数组的长度?
我实现这一目标的尝试如下:
function getMaterialsArrayLength(objName) {
for (i = 0; i < objectInfo.length; i++) {
if (objectInfo[i].name == objName) {
return objectInfo[i].materials.length
}
}
};
但是返回的错误是“无法读取未定义的属性材料”。有没有人有找到阵列长度的潜在解决方案?
如果之前已发布过,我道歉。
答案 0 :(得分:1)
var objectInfo = [{
name: "object1",
materials: [{
name: "wood",
quantity: 10
}, {
name: "stone",
quantity: 16
}],
}, {
name: "object2",
materials: [{
name: "wood",
quantity: 10
}, {
name: "stone",
quantity: 16
}, {
name: "bricks",
quantity: 100
}],
}]
function getMaterialsLength(objName) {
return objectInfo.find(o => o.name === objName).materials.length;
}
console.log(getMaterialsLength('object2'));
&#13;
可能想要添加一些错误检查。
答案 1 :(得分:0)
您无法获得不存在的数组的长度;更确切地说,您所查看的数组的元素是未定义的,因此没有找到长度的材料:
答案 2 :(得分:0)
只需通过索引访问对象:
var objectInfo = [
{
name:"object1",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}],
}, {
name:"object2",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}, {
name: "bricks",
quantity:100
}],
}];
console.log("objectInfo[0].materials.length: " + objectInfo[0].materials.length);
console.log("objectInfo[1].materials.length: " + objectInfo[1].materials.length);
&#13;
答案 3 :(得分:0)
使用lodash.js。
var objectInfo = [
{
name:"object1",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}],
}, {
name:"object2",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}, {
name: "bricks",
quantity:100
}],
}];
function getMaterialsLength(objName) {
_.each(objectInfo, function(obj) {
if (obj.name == objName) {
console.log(_.size(obj.materials));
}
});
}
getMaterialsLength('object2');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>