gpt4 book ai didi

Javascript:指定数组的长度并调用函数

转载 作者:行者123 更新时间:2023-11-28 19:04:45 25 4
gpt4 key购买 nike

我有一个函数,可以在数组中搜索指定的数字并返回搜索到的值、数组的长度以及数组所在的索引。

我有 3 个问题:

  1. 有没有办法创建一个调用我的 console.log 的函数,这样我就不必每次想要创建新数组时都编写它们?
  2. 在这种情况下如何获取数组的第一个值? (我的 console.log 中的“第一个数组元素”)
  3. 有没有一种方法可以让我的数组被赋值(假设 1 为“数字”),而无需键入中间的所有值?因为如果我的范围是 1-400,输入所有这些值会伤害我的手指;(。

代码:

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

最佳答案

每个问题:

  1. console.log 内部函数。在函数末尾返回搜索变量。请注意从循环到 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.
    }

    关于Javascript:指定数组的长度并调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929576/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com