如何将变量值与 Javascript 中的值数组匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27263593/
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
How to match a variable value against an array of values in Javascript?
提问by Anthony
I have an array of values with names:
我有一个带有名称的值数组:
names = ['Jim', 'Hyman', 'Fred']
I have also received a value from a function, which is a name in string form, such as:
我还收到了一个函数的值,它是一个字符串形式的名称,例如:
returnedValue = 'Jim'
How can I run the returnedValue string against the values of the names array and test for a match?
如何针对名称数组的值运行返回值字符串并测试是否匹配?
My feeling is that you would want to use the .filter method of the array prototype but I can't conceive of how to do it that way.
我的感觉是你会想要使用数组原型的 .filter 方法,但我无法想象如何做到这一点。
回答by Sharon
There is an indexOf method that all arrays have (except in old version of Internet Explorer) that will return the index of an element in the array, or -1 if it's not in the array:
所有数组都有一个 indexOf 方法(旧版本的 Internet Explorer 除外),它将返回数组中元素的索引,如果它不在数组中,则返回 -1:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
If you need to support old IE browsers, you can use polyfill this method using the code in the MDN article.
如果需要支持老的IE浏览器,可以使用polyfill这个方法使用MDN文章中的代码。
Copied from https://stackoverflow.com/a/12623295/2934820
回答by Shiala
the Array.indexOf method will return a value with the position of the returned value, in this case 0, if the value is not in array you'd get back -1 so typically if you wanna know if the returnedValue is in the array you'd do this if (names.indexOf(returnedValue) > -1) return true; Or you can do ~~ like Mr. Joseph Silber kindly explains in another thread
Array.indexOf 方法将返回一个包含返回值位置的值,在这种情况下为 0,如果该值不在数组中,您将返回 -1,因此通常如果您想知道返回值是否在数组中如果 (names.indexOf(returnedValue) > -1) 返回 true,就会这样做;或者你可以这样做~~就像约瑟夫西尔伯先生在另一个帖子中亲切地解释的那样
回答by Bobby
Check out this link on dictionaries https://www.w3schools.com/python/python_dictionaries.aspIf you have a variable whose value would match a string in the dictionary you can set a variable to equal that value. Here is a snip from some of my own code`
在字典上查看此链接 https://www.w3schools.com/python/python_dictionaries.asp如果您有一个变量的值与字典中的字符串匹配,您可以将变量设置为等于该值。这是我自己的一些代码的片段`
global element1
element1 = 1
elementdict = {
"H": 1.008,
"He": 4.00,
"Li": 6.49,
"Be": 9.01,
"B": 10.81,
"C": 12.01,
"N": 14.01,
"O": 16.00,
"F": 19.00,
"Ne": 20.18,
"Na": 22.99,
"Mg": 24.30
}
element1 = input("Enter an element to recieve its mass")
element1 = elementdict[element1]
print(element1)