Pra*_*eep 167 javascript titanium titanium-mobile
我正在使用Titanium,我的代码看起来像这样:
var currentData = new Array();
if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')
{
Ti.API.info("is exists " + currentData[index]);
return true;
}
else
{
return false;
}
Run Code Online (Sandbox Code Playgroud)
我正在向数组传递一个索引currentData
.我仍然无法使用上面的代码检测到不存在的元素.
tec*_*bar 334
使用 typeof arrayName[index] === 'undefined'
即
if(typeof arrayName[index] === 'undefined') {
// does not exist
}
else {
// does exist
}
Run Code Online (Sandbox Code Playgroud)
yes*_*nth 79
var myArray = ["Banana", "Orange", "Apple", "Mango"];
if (myArray.indexOf(searchTerm) === -1) {
console.log("element doesn't exist");
}
else {
console.log("element found");
}
Run Code Online (Sandbox Code Playgroud)
r3w*_*3wt 16
如果我错了,请有人纠正我,但AFAIK以下是正确的:
hasOwnProperty
“继承”自Object
hasOwnProperty
可以检查数组索引处是否存在任何内容。因此,只要上述情况属实,您可以简单地:
const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);
用法:
arrayHasIndex([1,2,3,4],4);
输出: false
arrayHasIndex([1,2,3,4],2);
输出: true
这正是in
运营商的用途。像这样使用它:
if (index in currentData)
{
Ti.API.info(index + " exists: " + currentData[index]);
}
Run Code Online (Sandbox Code Playgroud)
该接受的答案是错误的,它会给出假阴性如果在值index
是undefined
:
const currentData = ['a', undefined], index = 1;
if (index in currentData) {
console.info('exists');
}
// ...vs...
if (typeof currentData[index] !== 'undefined') {
console.info('exists');
} else {
console.info('does not exist'); // incorrect!
}
Run Code Online (Sandbox Code Playgroud)
===
这也可以很好地工作,使用against进行类型测试undefined
。
if (array[index] === undefined){ return } // True
Run Code Online (Sandbox Code Playgroud)
测试:
if (array[index] === undefined){ return } // True
Run Code Online (Sandbox Code Playgroud)
或者类似地:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
if (fruits["Cherry"] === undefined){
console.log("There isn't any cherry in the fruits basket :(")
}
Run Code Online (Sandbox Code Playgroud)
我不得不将 techfoobar 的答案包装在一个try
..catch
块中,如下所示:
try {
if(typeof arrayName[index] == 'undefined') {
// does not exist
}
else {
// does exist
}
}
catch (error){ /* ignore */ }
Run Code Online (Sandbox Code Playgroud)
...无论如何,这就是它在 chrome 中的工作方式(否则,代码会因错误而停止)。
归档时间: |
|
查看次数: |
339990 次 |
最近记录: |