javascript 或 jquery 中是否存在与 PHP array_key_exists 相等的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11776042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:18:29  来源:igfitidea点击:

is there an equalant to PHP array_key_exists in javascript or jquery

phpjavascriptjquery

提问by Kanishka Panamaldeniya

Possible Duplicate:
Checking if an associative array key exists in Javascript

可能的重复:
检查 Javascript 中是否存在关联数组键

I have a PHP code block . For a purpose I am converting this to a JavaScript block.

我有一个 PHP 代码块。出于某种目的,我将其转换为 JavaScript 块。

I have PHP

我有 PHP

if(array_key_exists($val['preferenceIDTmp'], $selected_pref_array[1]))

now I want to do this in jQuery. Is there any built in function to do this?

现在我想在 jQuery 中做到这一点。是否有任何内置功能可以做到这一点?

采纳答案by Flash

Note that objects (with named properties) and associative arrays are the same thing in javascript.

请注意,对象(具有命名属性)和关联数组在 javascript 中是一回事。

You can use hasOwnPropertyto check if an object contains a given property:

您可以使用hasOwnProperty检查对象是否包含给定的属性:

o = new Object();  
o.prop = 'exists'; // or o['prop'] = 'exists', this is equivalent 

function changeO() {  
  o.newprop = o.prop;  
  delete o.prop;  
}  

o.hasOwnProperty('prop');   //returns true  
changeO();  
o.hasOwnProperty('prop');   //returns false  

Alternatively, you can use:

或者,您可以使用:

if (prop in object)

The subtle difference is that the latter checks the prototype chain.

细微的区别在于后者检查原型链。

回答by Brian

In Javascript....

在 JavaScript 中....

if(nameofarray['preferenceIDTmp'] != undefined) {
    // It exists
} else {
    // Does not exist
}

回答by Pete

http://phpjs.org/functions/array_key_exists:323

http://phpjs.org/functions/array_key_exists:323

This is a great site for PHP programmers moving to js.

对于转向 js 的 PHP 程序员来说,这是一个很棒的网站。