我有一个默认的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
。
我要去哪里错了?
编辑:-
像这样的我想achieve-
{
"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];
如果属性值可以是假的,你必须检查与tableframe__top_content ===未定义|| tableframe__top_content ===空。