如何拆分字符串对象,然后连接并添加到数组

时间:2018-11-02 02:29:51

标签: javascript arrays split concatenation

此addtoTaskList函数需要将接收到的任务分为2个数组(?)或由逗号分隔的两个任务,然后将它们串联起来并将它们添加到task数组中。如当前代码所示,它将拆分值输出到taskList,但也输出非拆分副本,并在每次输入后清除任务列表,如下所示:  Duplicate Output

我非常感谢串联方面的帮助,谢谢!

"use strict";
var $ = function(id) { return document.getElementById(id); };

var tasks = [];

var displayTaskList = function() {
    var list = "";
    // if there are no tasks in tasks array, check storage
    if (tasks.length === 0) {
        // get tasks from storage or empty string if nothing in storage
        var storage = localStorage.getItem("tasks") || "";

        // if not empty, convert to array and store in global tasks variable
        if (storage.length > 0) { tasks = storage.split("|"); }
    }

    // if there are tasks in array, sort and create tasks string
    if (tasks.length > 0) {
       // tasks.sort();
        list = tasks.join("\n");
    }
    // display tasks string and set focus on task text box
    $("task_list").value = list;
    $("task").focus();
};

var addToTaskList = function() {   
    var task = $("task");
    if (task.value === "") {
        alert("Please enter a task.");
    } else {  

        // add task to array and local storage
        var partsOfStr = task.value.split(',');
        tasks = partsOfStr.concat(task.value);

        localStorage.tasks = tasks.join("|");

        // clear task text box and re-display tasks
        task.value = "";
        displayTaskList();
    }
};

var clearTaskList = function() {
    tasks.length = 0;
    localStorage.tasks = "";
    $("task_list").value = "";
    $("task").focus();
};

window.onload = function() {
    $("add_task").onclick = addToTaskList;
    $("clear_tasks").onclick = clearTaskList;    
    displayTaskList();
};

1 个答案:

答案 0 :(得分:1)

您正在尝试将数组(partsOfStr)与字符串(task.value)连接起来。也许您是要使用tasks而不是task.value

tasks = partsOfStr.concat(task.value);

应该是:

tasks = tasks.concat(partsOfStr);