通常我会期待一种String.contains()方法,但似乎没有一种方法.
检查这个的合理方法是什么?
我需要确定数组中是否存在值.
我使用以下功能:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
上面的函数总是返回false.
数组值和函数调用如下:
arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
Run Code Online (Sandbox Code Playgroud) 查找对象是否在数组中的最佳方法是什么?
这是我所知道的最佳方式:
function include(arr, obj) {
for(var i=0; i<arr.length; i++) {
if (arr[i] == obj) return true;
}
}
include([1,2,3,4], 3); // true
include([1,2,3,4], 6); // undefined
Run Code Online (Sandbox Code Playgroud) 有人能告诉我如何检测是否"specialword"出现在数组中?例:
categories: [
"specialword"
"word1"
"word2"
]
Run Code Online (Sandbox Code Playgroud) 我现在用来检查这个功能如下:
function inArray(needle,haystack)
{
var count=haystack.length;
for(var i=0;i<count;i++)
{
if(haystack[i]===needle){return true;}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
有用.我正在寻找的是,是否有更好的方法来做到这一点.
以下功能适用于Opera,Firefox和Chrome.但是,在IE8中它失败了if ( allowed.indexOf(ext[1]) == -1).
有谁知道为什么?有没有明显的错误?
function CheckMe() {
var allowed = new Array('docx','xls','xlsx', 'mp3', 'mp4', '3gp', 'sis', 'sisx', 'mp3', 'wav', 'mid', 'amr', 'jpg', 'gif', 'png', 'jpeg', 'txt', 'pdf', 'doc', 'rtf', 'thm', 'rar', 'zip', 'htm', 'html', 'css', 'swf', 'jar', 'nth', 'aac', 'cab', 'wgz');
var fileinput=document.getElementById('f');
var ext = fileinput.value.toLowerCase().split('.');
if ( allowed.indexOf(ext[1]) == -1)
{
document.getElementById('uploadsec').innerHTML = document.getElementById('uploadsec').innerHTML;
alert('This file type is not allowed!');
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个字符串数组和一个字符串.我想针对数组值测试此字符串并应用条件结果 - 如果数组包含字符串do"A",否则执行"B".
我怎样才能做到这一点?
目前我正在使用Angular 2.0.我有一个数组如下:
var channelArray: Array<string> = ['one', 'two', 'three'];
Run Code Online (Sandbox Code Playgroud)
如何在TypeScript中检查channelArray是否包含字符串'three'?
说我有这个
imageList = [100,200,300,400,500];
Run Code Online (Sandbox Code Playgroud)
哪能给我
[0]100 [1]200 等等
在JavaScript中有什么方法可以返回带有值的索引吗?
即我想要200的索引,我得到返回1.
var attr = ~'input,textarea'.indexOf( target.tagName.toLowerCase() )
? 'value'
: 'innerHTML'
Run Code Online (Sandbox Code Playgroud)
我在一个答案中看到了它,我以前从未见过它.
这是什么意思?
javascript ×10
arrays ×7
string ×3
indexof ×2
contains ×1
jquery ×1
substring ×1
syntax ×1
testing ×1
typescript ×1