我有一个函数,它在数组中搜索指定的数字,并返回搜索到的值,数组的长度以及数组所在的索引。
我有3个问题:
代码:
function include(arr, obj) {
for(var i=0; i< arr.length; i++) {
if (arr[i] == obj)
return [i, obj, arr.length];
}
}
var a = include([1,2,3,4,5,6,7,8,9,10,11,12,13,14], 6); // true
console.log("You searched for the value: " + a[1]);
console.log("The length of the array is: " + a[2]);
console.log("The Index of the value(" + a[1] + ") from " + "'first array element'" + " to " + (a[2]) + " is: " + a[0]);
console.log(include([1,2,3,4], 6)); // undefined
答案 0 :(得分:2)
每个问题:
indexOf
。function include(arr, obj) {
var returned = -1;
returned = arr.indexOf(obj); //get the index of the search criteria. It will return -1 if not found.
console.log("You searched for the value: " + obj); //obj will be the search value
if (returned != -1)
{
console.log("The length of the array is: " + arr.length); //arr.length gives us the length of the array;
console.log("The Index of the value ("+obj+"): " + returned); //returned gives us the index value.
}
else
{
console.log("It was not found");
}
return returned;
}
var a = include([1,2,3,4,5,6,7,8,9,10,11,12,13,14], 6); // true
您可以使用作为搜索条件的obj
参数和array.length
来获取数组的长度。我改进了使用array.indexOf
消除循环需求的功能。
for循环将执行此操作:
var newArray = [];
for (var i = 0; i < 400; i++)
{
array.push(i+1); //will push 400 values into the array.
}
答案 1 :(得分:1)
首先:你的意思是这样吗?
function report(a) {
console.log("You searched for the value: " + a[1]);
console.log("The length of the array is: " + a[2]);
console.log("The Index of the value(" + a[1] + ") from " + "'first array element'" + " to " + (a[2]) + " is: " + a[0]);
}
其次,要获取第一个数组元素,您可以访问 arr [0] 。为什么不从 include()返回arr本身呢?
function include(arr, obj) {
for(var i=0; i< arr.length; i++) {
if (arr[i] == obj)
return [i, obj, arr];
}
}
然后:
console.log("The Index of the value(" + a[1] + ") from " + arr[0] + " to " + arr.length + " is: " + a[0]);
至于定义一系列数字,JS没有本地方法可以做到这一点,但你可以使用Underscore库的_.range()方法,或像this一样扩展Javascript的数组!