在索引数组中查找值

时间:2017-02-14 18:31:34

标签: javascript arrays

我创建了一个检查嵌套数组的函数,以查看输入是否有效。要使输入有效,它在数组中不能具有两次相同的名称。 Arr [i] [0]包含作物的名称。

 function checkList(arr,cropName) {
    for (i = 0; i < 32; i++) {
        if (arr[i][0] == cropName){
            console.log("Name in Array")
            return true;
        } else {
            console.log("Name not in Array")
            return false;
        }

    }  
}

由于某种原因,这个算法不起作用,但我确信它应该,任何帮助都是值得赞赏的。我已经设置了一个JS小提琴,所以你可以根据需要查看它。

https://jsfiddle.net/qdzvr6z1/

2 个答案:

答案 0 :(得分:2)

您在第一次迭代时返回,因此您只需检查index 0

尝试

function checkList(arr,cropName) {
    for (i = 0; i < 32; i++) {
        if (arr[i][0] == cropName){
            console.log("Name in Array")
            return true;
        }
    }
    console.log("Name not in Array")
    return false;
}

答案 1 :(得分:0)

===更新的答案===
如果这很有用,请将我的答案投票。 :)

分享一些关于如何清理一些代码的想法(还有更多工作要做,但我需要停下来回到我的工作中),我重构并增强了你的解决方案。

在这里试一试 Fiddle

HTML:

<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;"></canvas><br>
<input type="color" id="currentColour" value="#ff0000">
<input type="text" id="cropName" placeholder="Please enter a color name"><br>
Mode:<br>
<div style="margin-left: 20px;">
    <input type="radio" id="modeAdd" name="mode" value="add" checked>Add</input><br>
    <input type="radio" id="modeClear" name="mode" value="clear">Clear</input>
</div>
<div>
    <p>Hover over a cell to see the values here:</p>
    <div style="margin-left: 20px;">
        Name: <input type="text" id="hoverName" /><br>
        Colour: <input type="text" id="hoverColour" />
    </div>
</div>

脚本:

    const defaultColour = "#ffffff";
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var numColours = 32;
    var colours = initialiseArray(numColours, defaultColour);

    function initialiseArray(qty, defaultColour) {
        var arr = [];
        for (i = 0; i < qty; i++) {
            arr.push({
                name: "",
                colour: defaultColour
            });
        };
        return arr
    };

    //DRAW GRID
    function drawGrid() {

        var step;
        ctx.setTransform(1, 0, 0, 1, 0.5, 0.5);
        ctx.beginPath();

        //Draw Vertical Lines
        for (step = 50; step < 400; step += 50) {
            ctx.moveTo(step, 0);
            ctx.lineTo(step, 200);
        }
        //Draw Horizontal Lines
        for (step = 50; step < 200; step += 50) {
            ctx.moveTo(0, step);
            ctx.lineTo(400, step);

            //Draw Dividers
            ctx.moveTo(200.5, 0);
            ctx.lineTo(200.5, 200);

            ctx.moveTo(0, 100.5);
            ctx.lineTo(400, 100.5);
        }

        ctx.stroke();
        ctx.setTransform(1, 0, 0, 1, 0, 0);
    }


    //GET MOUSE COORDINATES ON CANVAS
    function getMousePos(canvas, evt) {
        var rect = c.getBoundingClientRect();
        return {
            x: evt.clientX - rect.left,
            y: evt.clientY - rect.top
        };
    }

    function isColourNameProvided(name) {
        if (name) return true
        else return false;
    }

    // looks through an array of colour objects and returns true if the same name AND colour value combo exists
    function isDuplicateNameAndColourValue(newColourName, newColourValue) {
        return colours.some( c => c.name === newColourName && c.colour === newColourValue);
    }

    function isUserInputValid(arr, cropName, cropColour) {
        if (!isColourNameProvided(cropName)) {
            alert("Please set a name for the colour.");
            return false;
        }

        // Check to see if the combination of name and colour value already exists in the palette
        if (isDuplicateNameAndColourValue(cropName, cropColour)) {
            alert("That combination of NAME and COLOUR VALUE already exists in the palette.");
            return false;
        }

        return true;
    }

    function getMode() {
        var radios = document.getElementsByName("mode");
        for (i = 0; i < radios.length; i++) {
            if (radios[i].checked) return radios[i].value;
        }
        return null;
    }

    function updatePalette(event) {
        var cropName;
        var cropColour;
        var mousePos = getMousePos(c, event);
        var xPos = Math.floor(mousePos.x / 50) * 50 + 1;
        var yPos = Math.floor(mousePos.y / 50) * 50 + 1;
        var width = 49;
        var height = 49;
        var cellNum = Math.floor(mousePos.y / 50) * 8 + Math.floor(mousePos.x / 50)

        switch (getMode().toUpperCase()) {
            case "ADD":
                cropName = document.getElementById("cropName").value;
                cropColour = document.getElementById("currentColour").value;
                if (isUserInputValid(colours, cropName, cropColour)) {
                    updatePaletteCell(cellNum, cropName, cropColour, xPos, yPos, width, height);
                }
                break;
            case "CLEAR":
                cropName = "";
                cropColour = defaultColour;
                updatePaletteCell(cellNum, cropName, cropColour, xPos, yPos, width, height);
                break;
            default:
                alert("Unable to determine the mode.");
                break;
        }
    }

    function updatePaletteCell(cellNum, colourName, colourValue, xPos, yPos, width, height) {
        // paint the cell
        ctx.fillStyle = colourValue;
        ctx.fillRect(xPos, yPos, width, height);

        // store values for the cell
        colours[cellNum].name = colourName;
        colours[cellNum].colour = colourValue;
    }


    function showColourInfo(event) {
        var mousePos = getMousePos(c, event);
        var cellNum = Math.floor(mousePos.y / 50) * 8 + Math.floor(mousePos.x / 50)
        crop = colours[cellNum];
        if (crop) {
            document.getElementById("hoverName").value = crop.name;
            document.getElementById("hoverColour").value = crop.colour;
        }
    }

    c.addEventListener('mousemove', showColourInfo, false);
    c.addEventListener('click', updatePalette, false);

    drawGrid();

===原始答案===
丹尼尔给出的答案是正确的,但我认为它更好地重构为:

function checkList(arr,cropName) {
    var result = arr.some(x => {
        return (x[0] === cropName);
    });
    console.log("Duplicate found = ", result);
    return result;
}

注意:这个(以及你发布的那个)现在会在你的小提琴中返回true,因为你在更新单元格之前没有检查,所以总会找到它。

另一个快速提示: if (checkInput != false)通常是这样做的:if (checkInput),因为除了以下所有值都返回true:false, 0, "", null, undefined, and NaN