[英]How to check in an array if a value exists
I am building an javascript app with Backbone/Marionette (and Coffeescript) and I want to check if a value is contained within a textfield. 我正在使用Backbone / Marionette(和Coffeescript)构建一个javascript应用,我想检查文本字段中是否包含值。
If I do this it does not work: 如果我这样做不起作用:
questions = $("input[name='questions']").val().split(',')
if questions.indexOf(1) == -1
@ui.check.removeClass("green")
else
@ui.check.addClass("green")
If I do this it works (hard code the array): 如果我这样做,则可以工作(对数组进行硬编码):
questions = [1]
if questions.indexOf(1) == -1
@ui.check.removeClass("green")
else
@ui.check.addClass("green")
What am I doing wrong? 我究竟做错了什么?
From the fine String.prototype.split
manual : 从优良的
String.prototype.split
手册中 :
Return value
返回值
An array of strings split at each point where the separator occurs in the given string.
在给定字符串中出现分隔符的每个点处拆分的字符串数组。
and the fine Array.prototype.indexOf
manual : 和很好的
Array.prototype.indexOf
手册 :
Description
描述
indexOf()
comparessearchElement
to elements of the Array using strict equality (the same method used by the===
or triple-equals operator).indexOf()
使用严格相等(===
或三重等于运算符使用的相同方法indexOf()
将searchElement
与Array的元素进行比较。
So when you say this: 所以当你这样说:
questions = $("input[name='questions']").val().split(',')
if questions.indexOf(1) == -1
#...
you're searching an array of strings ( questions
) for a number using strict equality. 您正在使用严格相等性在字符串数组(
questions
)中搜索数字。 In JavaScript, 1 === '1'
will never be true (unlike 1 == '1'
) so your search will fail to find anything. 在JavaScript中,
1 === '1'
永远不会为真(与1 == '1'
),因此您的搜索将找不到任何东西。 Your hard-coded example works because question
is an array of numbers (not strings) there. 您的硬编码示例有效,因为
question
是那里的一个数字数组(而不是字符串)。
Either search for a string: 搜索一个字符串:
if questions.indexOf('1') == -1
or convert your strings to numbers before searching: 或在搜索之前将字符串转换为数字:
questions = $("input[name='questions']").val().split(',').map (s) -> +s
if questions.indexOf(1) == -1
Which approach you'd use depends on where the 1
comes from and what else you plan to do with questions
. 您将使用哪种方法取决于
1
来源以及您打算对questions
做些什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.