Javascript 给定一个数组,如何删除非';t包含在textarea值(字符串)中
我有一个带有以下when-console.log(cmotions)的数组: 然后我有一个文本区域(id=“comment”),其中包含: 我要做的是确定Cmotions记录是否在textarea值中。如果它们是dox,如果它们不是doy 用例。当它运行时,它会注意到Henry Ford不在文本区域,并将其删除 想法Javascript 给定一个数组,如何删除非';t包含在textarea值(字符串)中,javascript,jquery,arrays,Javascript,Jquery,Arrays,我有一个带有以下when-console.log(cmotions)的数组: 然后我有一个文本区域(id=“comment”),其中包含: 我要做的是确定Cmotions记录是否在textarea值中。如果它们是dox,如果它们不是doy 用例。当它运行时,它会注意到Henry Ford不在文本区域,并将其删除 想法 感谢循环遍历每个元素,并使用检查键处的名称是否存在于字符串中。indexOf: //cMentions is defined as in the question var comm
感谢循环遍历每个元素,并使用
检查键处的名称是否存在于字符串中。indexOf
:
//cMentions is defined as in the question
var commentValue = $('#comment').val();
for (var id in cMentions) {
if (cMentions.hasOwnProperty(id)) { // Ignore native methods
var searchTerm = cMentions[id]; // Search for the existence of this name
if (commentValue.indexOf(searchTerm) == -1) {
cMentions[id] = void 0; // Overwriting by `void 0` = `undefined`
delete cMentions[id]; // In case the variable still exists
}
}
}
循环遍历每个元素,并使用
.indexOf
,检查键处的名称是否存在于字符串中:
//cMentions is defined as in the question
var commentValue = $('#comment').val();
for (var id in cMentions) {
if (cMentions.hasOwnProperty(id)) { // Ignore native methods
var searchTerm = cMentions[id]; // Search for the existence of this name
if (commentValue.indexOf(searchTerm) == -1) {
cMentions[id] = void 0; // Overwriting by `void 0` = `undefined`
delete cMentions[id]; // In case the variable still exists
}
}
}
这很好,但这使得数组项如下所示:19:未定义---我如何才能真正删除array@RachelaMeadows在我的浏览器中,
19
作为条目消失。我已经用delete
更新了答案,以防答案没有更新。为什么要将某个内容设置为void 0
?如果您想要未定义的
,您不能将某个值设置为未定义的
?在这种情况下,似乎只需要delete
操作符。不需要void 0
赋值。@jfriend00与null
不同,未定义的
可以被任意值覆盖<代码>变量未定义=1;警报(未定义)显示1
,而不是未定义
。用null
替换undefined
,您将得到一个错误。我不确定从何处获得“更正确”的信息。如果需要,我会坚持将某个值设置为null
或undefined
(通常我使用null
),因为这样看起来可读性更高,而且一直有效。在这种情况下,根本不需要它。只需使用delete
行,这在我看来更具可读性。这很好,但这会使数组项如下所示:19:undefined---我如何实际删除array@RachelaMeadows在我的浏览器中,19
作为条目消失。我已经用delete
更新了答案,以防答案没有更新。为什么要将某个内容设置为void 0
?如果您想要未定义的
,您不能将某个值设置为未定义的
?在这种情况下,似乎只需要delete
操作符。不需要void 0
赋值。@jfriend00与null
不同,未定义的
可以被任意值覆盖<代码>变量未定义=1;警报(未定义)显示1
,而不是未定义
。用null
替换undefined
,您将得到一个错误。我不确定从何处获得“更正确”的信息。如果需要,我会坚持将某个值设置为null
或undefined
(通常我使用null
),因为这样看起来可读性更高,而且一直有效。在这种情况下,根本不需要它。只需使用delete
行,它在我看来更具可读性。
//cMentions is defined as in the question
var commentValue = $('#comment').val();
for (var id in cMentions) {
if (cMentions.hasOwnProperty(id)) { // Ignore native methods
var searchTerm = cMentions[id]; // Search for the existence of this name
if (commentValue.indexOf(searchTerm) == -1) {
cMentions[id] = void 0; // Overwriting by `void 0` = `undefined`
delete cMentions[id]; // In case the variable still exists
}
}
}