我有一个默认的 JSON 文件:-
{
"_name":"__tableframe__top",
"_use-attribute-sets":"common.border__top",
"__prefix":"xsl"
}
我试图通过创建一个数组来推送一些值,但在推送数据后我得到了我的数组未定义值
{
"_name":"__tableframe__top",
"_use-attribute-sets":"common.border__top",
"__prefix":"xsl",
"attribute":[undefined]
}
首先,我检查对象是否包含数组,如果不包含则创建数组。如果已经有一个数组,那么什么也不做。
if(!($scope.tObj.stylesheet["attribute-set"][4].attribute instanceof Array)){
const tableframe__top_content = $scope.tObj.stylesheet["attribute-set"][4].attribute;
$scope.tObj.stylesheet["attribute-set"][4].attribute = [tableframe__top_content];
}
在此之后,我检查数组中是否已存在 _name
= something
的属性。如果没有,则推送。
var checkTableFrameTopColor = obj => obj._name === 'border-before-color';
var checkTableFrameTopWidth = obj => obj._name === 'border-before-width';
var checkTableFrameTopColor_available = $scope.tObj.stylesheet["attribute-set"][4].attribute.some(checkTableFrameTopColor);
var checkTableFrameTopWidth_available = $scope.tObj.stylesheet["attribute-set"][4].attribute.some(checkTableFrameTopWidth);
if( checkTableFrameTopColor_available === false && checkTableFrameTopWidth_available === false ){
$scope.tObj.stylesheet["attribute-set"][4].attribute.push({
"_name": "border-before-color",
"__prefix": "xsl",
"__text": "black"
},{
"_name": "border-before-width",
"__prefix": "xsl",
"__text": "1pt"
}
);
console.log("pushed successfully");
console.log($scope.tObj);
}
我在数组上得到空值并出现错误TypeError: Cannot read property '_name' of undefined at checkTableFrameTopColor
。
我哪里出错了?
编辑:-
像这样我想要实现-
{
"attribute":[
{"_name":"font-weight","__prefix":"xsl","__text":"bold"},
{"_name":"color","__prefix":"xsl","__text":"black"}
],
"_name":"__tableframe__top",
"_use-attribute-sets":"common.border__top",
"__prefix":"xsl"
}
最佳答案
我必须猜测,但让我将其作为答案发布,以便我可以使用格式......
给定:
const input = {
"_name":"__tableframe__top",
"_use-attribute-sets":"common.border__top",
"__prefix":"xsl"
}
注意:input.attribute 的值未定义。
if(!($scope.tObj.stylesheet["attribute-set"][4].attribute instanceof Array)){
const tableframe__top_content = $scope.tObj.stylesheet["attribute-set"][4].attribute;
$scope.tObj.stylesheet["attribute-set"][4].attribute = [tableframe__top_content];
}
..因此,如果此输入是您在 if 语句中访问的内容
input.attribute instanceof Array => false
这是真的,你的代码块将被执行,它说:
const example.attribute = [input.attribute]
// example.attribute == [undefined]
如果我理解正确的话,你可以这样解决:
$scope.tObj.stylesheet["attribute-set"][4].attribute = (!tableframe__top_content)
? []
: [tableframe__top_content];
如果属性值可能为 false,则必须检查 tableframe__top_content === undefined || tableframe__top_content === null。
关于javascript - 获取数组中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54515034/