Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 views
in Technique[技术] by (71.8m points)

javascript - Check if an input is an array or not, and print the result

The code is not returning the expected result: I want to return "true" if it is an array on the "checkArray" div and "false" if it is not, depending on the user input.

<input type="text" id="data" placeholder="Insert data">
<button type="submit" onclick="checkArray()">Check</button>
<div id="checkArray"></div>
<script>
function is_array(data) {
    if (data instanceof Array) {
        return true;
    } else {
        return false;
    }
};
function checkArray() {
    var data = document.getElementById("data").value;
    document.getElementById("checkArray").innerHTML = is_array(data);
}
question from:https://stackoverflow.com/questions/65891060/check-if-an-input-is-an-array-or-not-and-print-the-result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are only looking for opening and closing array brackets at the start and end of your input value, you could replace your is_array(data) function with the below code. Although the type of your input value will be string anyway.

function is_array(data) {
    return data[0] + data[data.length - 1] === "[]"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...