【问题标题】:How to split string object and then concatenate and add to array如何拆分字符串对象,然后连接并添加到数组
【发布时间】:2018-11-02 02:29:51
【问题描述】:

这个 addtoTaskList 函数需要将接收到的任务分成 2 个数组(?)或用逗号分隔的两个任务,然后将它们连接起来并添加到任务数组中。按照目前的代码,它将拆分值输出到任务列表,但也输出一个非拆分副本,并在每个条目后清除任务列表,如下所示:

我主要需要连接方面的帮助,谢谢!

"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();
};

【问题讨论】:

  • 虽然没有必要,但我建议您使用 JSON.stringify(tasks) 和 JSON.parse(storage) 而不是使用“|”加入和拆分数组人物。这样,如果有人输入“|”添加任务时,它不会向您的任务数组添加额外的值。
  • 谢谢!!!很抱歉浪费你的时间:(你是我的英雄

标签: javascript arrays split concatenation


【解决方案1】:

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

tasks = partsOfStr.concat(task.value);

应该是:

tasks = tasks.concat(partsOfStr);

【讨论】:

  • 谢谢 Jason,不幸的是我之前尝试过,结果没有输出...
  • @JamesHolloway 我似乎无法重现您的问题。您是否确保将concat() 操作的结果分配给任务? concat() 不会修改原始数组,它只是返回一个新的串联数组。
  • 哦,杰森勋爵,我很抱歉,您的解决方案奏效了!我有一个大写错误-oof!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-27
相关资源
最近更新 更多