简体   繁体   English

如何从数组中获取 X 个唯一项

[英]How do i get the X number of unique items from an array

Im trying to change the X number in the for loop based on what array this function is using.我试图根据此函数使用的数组更改 for 循环中的 X 数。 The function gets x random values from an array which he then checks if it isnt the same value and if it isnt the same value he then returns the 2 random values in the array.该函数从数组中获取 x 个随机值,然后检查它是否不是相同的值,如果它不是相同的值,则返回数组中的 2 个随机值。 i tried doing a switch statement like this:我试着做一个像这样的 switch 语句:

switch(this) {
   case array1:
       x = 2;
       break;
   case array2:
       x = 3;
       break;
}

code代码

Array.prototype.random = function () {
    let result = [];
    let bool = false;
    let x = 0;
    for (var i = 0; i < x; i++) {
        result.push(this[Math.floor(Math.random() * this.length)]);
    }
    while (bool == false) {
        if (result[0] === result[1]) {
            result.pop();
            result.push(this[Math.floor(Math.random() * this.length)]);
        } else {
            bool = true;
        }
    }
    return result[0] + "  +  " + result[1];
}

Remove "()this" because this is a syntax error.删除“()this”,因为这是一个语法错误。

You're trying to do a math calculation:您正在尝试进行数学计算:

Math.random() * this.length

Not a syntax error:不是语法错误:

Math.random()this.length

And also, you're for loop is not doing anything, because i counts up to x only if i is lower than x .而且,你的循环没有做任何事情,因为i计数到x只有当i是低于x But i and x are both 0, so it will not do anything.但是ix都是 0,所以它不会做任何事情。 If you're trying to make the for loop go up 1 time, just use "2", for 2 results instead of "0".如果你试图让 for 循环上升 1 次,只需使用“2”,2 个结果而不是“0”。

Next, result.pop() is just returning the value of "result" popped.接下来, result.pop()只是返回弹出的“result”的值。

Remove that.去掉那个。

Getting the amount of unique items in the array looks something like获取数组中唯一项的数量看起来像

function getUniqueCount(list){
  let storage={}, count=0;
  for(let i=0; i<list.length; i++){
    if(!storage[list[i]]){
      storage[list[i]]=true; count++;
    }
  }
  return count;
}

But I'm not sure if that number would help you because you're not saying what you want your function to do但我不确定这个数字是否对你有帮助,因为你没有说你想要你的功能做什么

I'm not sure what the x variable is supposed to be.我不确定x变量应该是什么。 If you just want to return 2 random elements from the array, there's no need for that variable or the result array.如果您只想从数组中返回 2 个随机元素,则不需要该变量或result数组。 Just use two variables.只需使用两个变量。

 Array.prototype.random = function() { let item1 = this[Math.floor(Math.random() * this.length)]; while (true) { let item2 = this[Math.floor(Math.random() * this.length)]; if (item2 != item1) { return item1 + " + " + item2; } } } console.log([1, 2, 3, 4, 5, 6, 7, 8].random());

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

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