简体   繁体   English

使用Java脚本在数组中重复值的函数

[英]Function to reiterate values in an array using Javascript

I need to create a function that inputs a new value into an empty array, and then the value stays in the array, even if the value changes. 我需要创建一个将新值输入到空数组中的函数,然后该值将保留在数组中,即使该值发生更改也是如此。 Let me explain with an example and I have so far: 让我用一个例子来解释,到目前为止,我已经:

var arr = [];
arr.unshift("f");
if (arr.length > 6) {
   arr.pop();
}
console.log(arr);

arr.unshift("e");
if (arr.length > 6) {
  arr.pop();
}
console.log(arr);

arr.unshift("d");
if (arr.length > 6) {
  arr.pop();
}
console.log(arr);

arr.unshift("c");
if (arr.length > 6) {
  arr.pop();
}
console.log(arr);

arr.unshift("b");
if (arr.length > 6) {
  arr.pop();
}
console.log(arr);

arr.unshift("a");
if (arr.length > 6) {
  arr.pop();
}
console.log(arr);
arr.unshift("z");
if (arr.length > 6) {
  arr.pop();
}
console.log(arr);

Here in the empty array a new value gets inputted in first position and stays in the array arr. 在这里,在空数组中,新值输入到第一个位置,并保持在数组arr中。 This is what I get in the console: 这是我在控制台中得到的:

(6) ["f"]    
(6) ["e", "f"]    
(6) ["d", "e", "f"]    
(6) ["c", "d", "e", "f"]    
(6) ["b", "c", "d", "e", "f"]    
(6) ["a", "b", "c", "d", "e", "f"]    
(6) ["z", "a", "b", "c", "d", "e"]

which is exactly what I want to achieve. 这正是我想要实现的目标。 Instead of these values I need a var that will get updated regularly. 除了这些值,我需要一个可以定期更新的变量。

var newValue = value_to_be_updated;

function myFunction(newValue) {
    var arr = [];
    arr.unshift(newValue);
    return arr
}

if (arr.length > 6) {
    arr.pop();
}

My goal is to reduce the above code and make it a function, but couldn't find anything helpful. 我的目标是减少上面的代码并使之成为函数,但找不到任何有用的方法。 Also is there any way the value inputted stays in the array, even if removed from the var? 即使将输入的值从var中删除,还有什么方法可以将其保留在数组中?

Any help will be hugely appreciated!!!!! 任何帮助将不胜感激!

Thanks in advance 提前致谢

You should be getting the new value dynamically using for example a prompt, if you are expecting the value of arr to remain the same after changing the source code that would not work. 如果您期望更改更改后的源代码后, arr的值保持不变,则应该使用提示来动态获取新值。 Still has @gurvinder372 said your function should look something like this 还有@ gurvinder372说你的函数应该看起来像这样

var arr = [];
function myFunction(newValue) {
  arr.unshift(newValue);
  if (arr.length > 6) {
    arr.pop();
  }
  return arr
}

then to use it you can do something like this 然后使用它,你可以做这样的事情

for (var i = 0; i<8; i++){
   var value = prompt('enter char');
   myFunction(value);
}

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

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