简体   繁体   English

我想打印数组的最后一个 'n' 元素

[英]I want to print the last 'n' elements of an array

I am writing a JavaScript function to get the last 'n' elements of the array.我正在编写一个 JavaScript 函数来获取数组的最后一个 'n' 元素。 If array has 6 elements and if user gives 4, it has to return last 4 elements.如果数组有 6 个元素,如果用户给出 4 个元素,则它必须返回最后 4 个元素。 If user gives 'n' which is greater than the number of elements in the array, then it should return all elements.如果用户给出的 'n' 大于数组中的元素数,则它应该返回所有元素。

The problem is if If the array has 8 elements and I give number 10. The result is : undefined undefined 1 2 3 4 5 6 7 8问题是如果数组有 8 个元素,我给出数字 10。结果是: undefined undefined 1 2 3 4 5 6 7 8

I want to display only the numbers without "undefined".我只想显示没有“未定义”的数字。

Thanks谢谢

HTML code HTML代码

The array is :数组是:

1,2,3,4,5,6,7,8

        <br>
        x:
        <input type="number" id="x" value="2" >
        <br>
        <button onclick="elements()"> Get the elements </button>

        <p id="result"></p>

    <script src="ex10.js"></script>

JavaScript code JavaScript 代码

 var Elements = new Array(1,2,3,4,5,6,7,8);

    function elements(){
    var x = document.getElementById("x").value;

    for(var i=Elements.length - x; i <=Elements.length-1; i++)
    {
    document.getElementById("result").innerHTML += Elements[i] + " ";
    }

}

You could take slice with a negative count from the end.你可以从最后取负数slice Then join the elements for a formatted output.然后join格式化输出的元素。

Some links:一些链接:

 var array = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(array.slice(-4).join(' '));

Try using .slice method with a negative start index:尝试使用带有负起始索引的.slice方法:

 var Elements = new Array(1,2,3,4,5,6,7,8); var last4 = Elements.slice(-4) console.log(last4)

You can just reassign x to be the length of the array if x is greater than the size of the array.如果 x 大于数组的大小,您可以将 x 重新分配为数组的长度。 Now you will at most print the entire array and at least print x.现在您最多将打印整个数组并至少打印 x。

var x = document.getElementById("x").value;

if(x > Elements.length)  // add this
    x = Elements.length;

for(var i=Elements.length - x; i <=Elements.length-1; i++)
{
    document.getElementById("result").innerHTML += Elements[i] + " ";
}

There are other ways to achieve why you need, for example by using .slice() , .map() etc.还有其他方法可以实现您的需求,例如使用.slice().map()等。

If you need to stick to for loops, thn Math.min() can come handy:如果您需要坚持使用for循环,那么Math.min()可以派上用场:

 const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const elX = document.getElementById("x"); const elR = document.getElementById("result"); function elements() { const x = parseInt(elX.value, 10); // use parseInt with radix! const min = Math.min(arr.length, x); let html = ""; for (var i = arr.length - min; i <= arr.length - 1; i++) { html += arr[i] + " "; } elR.innerHTML = html; // Insert into DOM only once! }
 x: <input type="number" id="x" value="2"> <button onclick="elements()">Get the last N elements</button> <p id="result"></p>

Here's the example using .slice() and .map()这是使用.slice().map()的示例

 const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const elX = document.getElementById("x"); const elR = document.getElementById("result"); function elements() { const x = parseInt(elX.value, 10); elR.innerHTML = arr.slice(-x).map(n => `Item:${n}`).join('<br>'); }
 x: <input type="number" id="x" value="2"> <button onclick="elements()">Get the last N elements</button> <p id="result"></p>

You want to make sure i is within range of the array.你想确保i在数组的范围内。 Elements.length - x needs to be equal or superior to 0. Elements.length - x需要等于或大于 0。

Like other said you can (should ?) use slice but since you seem to be practicing with for loops then you better stick with it.就像其他人说的那样,您可以(应该?)使用切片,但由于您似乎正在练习 for 循环,因此您最好坚持使用它。

var Elements = new Array(1,2,3,4,5,6,7,8);

function elements(){
    var x = document.getElementById("x").value;

    for(var i=Math.max(Elements.length - x, 0); i <=Elements.length-1; i++)
    {
        document.getElementById("result").innerHTML += Elements[i] + " ";
    }

}

 const count = 5; var Elements = new Array(1,2,3,4,5,6,7,8); var result = Elements.slice(count > Elements.length ? 0 : Elements.length - count,Elements.length) console.log(result)

const drivers = ['Sally', 'Bob', 'Freddy', 'Claudia'];

  function returnFirstTwoDrivers(drivers) {
  return drivers.slice(0,2) 
  }

    function returnLastTwoDrivers(drivers) {
    return drivers.slice(-2)
  }
  

document.getElementById("mocha").innerHTML = 'ARRAY 1: ' + returnFirstTwoDrivers(drivers) + '<br/>ARRAY 2: ' + returnLastTwoDrivers(drivers);

Code Output代码输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM