检查数组位置是否真的未定义
Check if an array position is really undefined or not
我正在尝试检查JSON.stringify(obj, callback)
回调中给定的值是否真的未定义。它的问题是尚未定义数组值。
var a = new Array(3);
a[0] = true;
a[2] = undefined;
a.length; // 3
a.hasOwnProperty(0); // true
a.hasOwnProperty(1); // false
a.hasOwnProperty(2); // true
a.hasOwnProperty(3); // false
(a[1] === a[2]) // true
有什么想法可以检测位置[1]
是否已定义?因为数组有3个元素用于JSON.stringify算法。
找出数组中分配的(不一定是定义的)索引的一种方法是迭代器函数,如forEach
,它忽略空槽:
var a = new Array(3);
a[0] = true;
a[2] = undefined;
defined = []
a.forEach(function(_, n) { defined.push(n) })
alert(defined)
因此,您可以使用伪迭代器只返回已分配的项:
a = []
a[1] = 11
a[2] = 22
a[3] = undefined
a[5] = 55
a[99] = 99
s = JSON.stringify(a, function(key, value) {
if(Array.isArray(value))
return value.filter(function() { return 1 });
return value;
});
alert(s)
JSON.stringify()
中的replacer
参数具有以下内容:
- 参数
key
-要字符串化的属性的名称 - 参数
value
-要字符串化的属性的值 - 绑定
this
-包含要字符串化的属性的当前对象
您可以"调试"每个调用并打印如下值:
var a = new Array(3);
a[0] = true;
a[2] = undefined;
JSON.stringify(a, function(key, value) {
var s = ''n-----------'
s += ''nkey: ' + JSON.stringify(key);
s += ''nvalue: ' + JSON.stringify(value);
s += ''nthis: ' + JSON.stringify(this);
document.getElementById('result').innerHTML += s;
return value;
});
<pre id="result"></pre>
这意味着您可以访问this
中的原始数组
因此,您可以按照您在问题中建议的组合使用简单的hasOwnProperty
来确定它是否已定义:
var a = new Array(3);
a[0] = true;
a[2] = undefined;
var result = JSON.stringify(a, function(key, value) {
// value is undefined, either explicitly or really not set
if(typeof value === "undefined") {
// property not set at all
if(!this.hasOwnProperty(key)) {
return "really undefined";
}
else {
// returning undefined from the callback will set the value to null,
// so I give another value here to demonstrate the check
return "explicitly undefined";
}
}
// has an actual value so just return it
return value;
}, " ");
document.getElementById('result').innerHTML = result;
<pre id="result"></pre>
正如我在代码注释中提到的,需要强调的是,您必须小心从回调返回undefined
。正如我在顶部链接的MDN文章所述:
注意:不能使用replacer函数从数组中删除值。如果返回undefined或函数,则使用null。
这就是调试代码段显示数组条目1和2为null的原因。
相关文章:
- 为什么“;未定义的“;在JavaScript中结束循环
- 要求未定义JS回调参数
- 如何检查管道中未定义的项目
- TypeError:无法读取属性'推'未定义的JavaScript
- $window.ga在AngularJS事件中未定义
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 无法获取属性'selectedIndex'的未定义引用或null引用
- 如何消除代码中的未定义和其他问题
- 未捕获的ReferenceError:$未定义
- this.router在AngularJS 2中未定义
- 未捕获的类型错误:无法读取属性'删除'的未定义
- 节点fs.stat名称未定义
- 尝试在PHP中回显输入文本时出现未定义的索引错误
- Jquery未定义函数正在停止其他操作
- AngularJS指令出错-无法读取属性'编译'的未定义
- 为什么typeof的数组的数组的未定义值返回为“0”;未定义的“;我的条件不认为是真的
- 检查数组位置是否真的未定义
- 检测 Javascript 变量是否真的未定义
- JS说我有一个未定义的对象.真的需要一些帮助来解决这个问题吗