我正在尝试创建一个从多维数组中删除空值的函数,但它不能很好地工作.它不会穿透到最后一层数组,并且在两个空值相邻时不会删除.
function isArray(obj) {
// http://stackoverflow.com/a/1058753/1252748
return Object.prototype.toString.call(obj) === '[object Array]';
}
function removeEmptyArrayElements(obj) {
for (key in obj) {
if (obj[key] === null) {
obj = obj.splice(key, 1);
}
var isArr = isArray(obj[key]);
if (isArr) {
removeEmptyArrayElements(obj[key]);
}
}
return obj;
}
Run Code Online (Sandbox Code Playgroud) 我使用Object.prototype.toString.call来识别变量类型.我希望以下行为:
Object.prototype.toString.call({}) => [object Object]
Object.prototype.toString.call([]) => [object Array]
Object.prototype.toString.call(undefined) => [object Undefined]
Object.prototype.toString.call(null) => [object Null]
Run Code Online (Sandbox Code Playgroud)
这通常工作正常,但我目前面临的情况(在Internet Explorer)其中两个Object.prototype.toString.call(undefined)与Object.prototype.toString.call(null)返回[对象对象],我不明白为什么.我试图在jsfiddle.net上复制它但不能,所以我假设我处于特定的怪癖模式.
我的问题:
可能重复:
如何检测变量是否为数组
当我需要测试变量是否是一个数组时(例如函数中的输入参数可能是对象或数组)我通常使用这段代码
typeof(myVar) === 'object' && myVar.length !== undefined;
Run Code Online (Sandbox Code Playgroud)
这是正确的方法,还是有更有效的方法,考虑到即使 myVar instanceof Array 速度更快,也应该避免因iframe问题而避免?
我很好奇为什么IE8会在线路上窒息
if (isArray(obj))
Run Code Online (Sandbox Code Playgroud)
这是我在IE8 javascript控制台中得到的:
>>obj
{...}
>>typeof(obj)
"object"
>>Object.prototype.toString.call(obj)
"[object Array]"
Run Code Online (Sandbox Code Playgroud)
乃至
>>obj.length
7
Run Code Online (Sandbox Code Playgroud)
然而,
>>isArray(obj)
Object expected
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况(ie8不支持isArray?)以及解决它的最佳方法是什么?
我正在尝试使用新版本的Angular for IE8.我知道它没有得到官方的支持,但是我会尝试使应用程序更好或更差.
谢谢.
javascript methods internet-explorer internet-explorer-8 angularjs
我正在使用查询字符串库来解析URL中的查询参数。当查询参数为形式时?foo=bar,lib返回如下对象:
{
foo: bar
}
Run Code Online (Sandbox Code Playgroud)
当为形式时?foo=bar1,bar2,对象如下所示:
{
foo: [bar1, bar2]
}
Run Code Online (Sandbox Code Playgroud)
我想myFunction在每个元素上应用函数myObject.foo以获得类似[myFunction(bar)]或[myFunction(bar1), myFunction(bar2)]
有没有办法像这样轻松地做到这一点
myObject.foo.mapOrApply(myFunction)
Run Code Online (Sandbox Code Playgroud)
无需检查这是否是数组?
现在,我被迫以这种方式这样做,我发现这很不美观:
Array.isArray(myObject.foo)
? myObject.foo.map(myFunction)
: [myFunction(myObject.foo)];
Run Code Online (Sandbox Code Playgroud)