简体   繁体   English

将变量分配给数组中的值

[英]assigning a variable to a value from an array

I have a variable (paddleOneVelocityY) that I want to change to one of the values in an array ( paddleSpeeds), based on the position of the value of another variable (trialWindow) in another array (trialValues).我有一个变量 (paddleOneVelocityY),我想根据另一个数组 (trialValues) 中另一个变量 (trialWindow) 的值的 position 将其更改为数组 (paddleSpeeds) 中的一个值。

This code would mean that the value of paddleOneVelocityY would change if the value of trialWindow appears in the trialValues array, and its position in the array would determine which value from paddleSpeeds would be assigned to paddleOneVelocityY.这段代码意味着如果 trialWindow 的值出现在 trialValues 数组中,paddleOneVelocityY 的值将会改变,并且它在数组中的 position 将确定 paddleSpeeds 中的哪个值将分配给 paddleOneVelocityY。 For example, if trialWindow's value is the 3rd value in trialValues, the 3rd value in paddleSpeeds would be assigned as the new value of paddleOneVelocityY.例如,如果 trialWindow 的值是 trialValues 中的第 3 个值,则 paddleSpeeds 中的第 3 个值将被分配为 paddleOneVelocityY 的新值。

So far, I have written code to identify whether a value appears in the trialValues array and change the paddle colour based on this which is working but I've only put a random number placeholder to change paddleOneVelocityY.到目前为止,我已经编写了代码来识别一个值是否出现在 trialValues 数组中,并根据这个工作改变桨颜色,但我只放置了一个随机数占位符来改变 paddleOneVelocityY。 I'm guessing I'll need to write more code to identify the index of the value of trialWindow in trialValues and then use that index to assign the value at the same index in paddleSpeeds to paddleOneVelocityY, I'm just not sure how to implement this...我猜我需要编写更多代码来识别trialValues中trialWindow值的索引,然后使用该索引将paddleSpeeds中相同索引处的值分配给paddleOneVelocityY,我只是不确定如何实现这个...

const trialValues = [30, 60, 90, 120, 150, 180, 210];
const paddleSpeeds = [5, 20, 30, 10, 5, 15, 25];

function includes(array, searchElement) {
        for (let element of array)
        if (element === searchElement)
            return true;
        return false;
    }


function userSpeed() {
    if (includes(trialValues, trialWindow))
    {colourChange = '#ff00ff', paddleOneVelocityY = getRandomNumber(5, 35), console.log({paddleOneVelocityY})}
else {colourChange = 'white'}

Use indexOf:使用 indexOf:

const index = trialValues.indexOf(120); // will return 3

then然后

paddleSpeeds[index] = 'newValue';

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

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