문제

이 코드가 있다고 가정합니다.

var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;

이제 "lastname"을 제거하고 싶다면? ....
myArray["lastname"].remove()?

(요소의 수가 중요하고 물건을 깨끗하게 유지하고 싶기 때문에 요소가 사라져야합니다.)

도움이 되었습니까?

해결책

JavaScript에서 "Delete"키워드를 사용하십시오.

delete myArray["lastname"];

편집하다:

일부 JavaScript 엔진에서는 삭제 키워드가 컴파일 / JIT 최적화를 취소하므로 성능이 손상 될 수 있습니다.

http://www.html5rocks.com/en/tutorials/speed/v8/ http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javaScript/

다른 팁

JavaScript의 모든 객체는 HashTables/Ameriative Array로 구현됩니다. 따라서 다음은 다음과 같습니다.

alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);

그리고 이미 지적한 바와 같이, 당신은 delete 두 가지 방법으로 사용할 수있는 키워드 :

delete myObj["SomeProperty"];
delete myObj.SomeProperty;

추가 정보가 도움이되기를 바랍니다 ...

이전 답변 중 어느 것도 JavaScript에 처음으로 연관 배열이 없다는 사실을 다루지 않습니다. array 따라서 유형을 참조하십시오 typeof.

JavaScript가 가진 것은 동적 특성을 가진 객체 인스턴스입니다. 속성이 배열 객체 인스턴스의 요소와 혼동되면 Bad Things ™가 발생합니다.

문제

var elements = new Array()

elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]

console.log("number of elements: ", elements.length)   // returns 2
delete elements[1]
console.log("number of elements: ", elements.length)   // returns 2 (?!)

for (var i = 0; i < elements.length; i++)
{
   // uh-oh... throws a TypeError when i == 1
   elements[i].onmouseover = function () { window.alert("Over It.")}
   console.log("success at index: ", i)
}

해결책

당신에게 폭발하지 않는 보편적 인 제거 기능을 갖추려면 다음을 사용하십시오.

Object.prototype.removeItem = function (key) {
   if (!this.hasOwnProperty(key))
      return
   if (isNaN(parseInt(key)) || !(this instanceof Array))
      delete this[key]
   else
      this.splice(key, 1)
};

//
// Code sample.
//
var elements = new Array()

elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]

console.log(elements.length)                        // returns 2
elements.removeItem("prop")
elements.removeItem(0)
console.log(elements.hasOwnProperty("prop"))        // returns false as it should
console.log(elements.length)                        // returns 1 as it should

객체 만 삭제하면 분리되지만 여전히 배열 길이를 동일하게 유지합니다.

제거하려면 다음과 같은 작업을 수행해야합니다.

array.splice(index, 1);

허용 된 대답은 정확하지만 왜 작동하는지 설명이 누락되었습니다.

우선, 귀하의 코드는 이것이 아니다 배열:

var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;

모든 객체 (포함 Arrays) 이런 식으로 사용할 수 있습니다. 그러나 표준 JS 배열 함수 (팝, 푸시, ...)가 객체에서 작동 할 것으로 기대하지 마십시오!

허용 답변에서 말했듯이 delete 객체에서 항목을 제거하려면 :

delete myObject["lastname"]

객체 (연관 배열 / 사전)를 사용하거나 배열 (맵)을 사용하는 경로를 결정해야합니다. 두 사람을 섞지 마십시오.

사용 방법 splice 객체 배열에서 항목을 완전히 제거하려면 :

Object.prototype.removeItem = function (key, value) {
    if (value == undefined)
        return;

    for (var i in this) {
        if (this[i][key] == value) {
            this.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");

당신은 객체를 사용하고 있으며, 당신은 처음에 연관 배열이 없습니다. 연관 배열을 사용하면 항목을 추가하고 제거하는 것은 다음과 같습니다.

    Array.prototype.contains = function(obj) 
    {
        var i = this.length;
        while (i--) 
        {
            if (this[i] === obj) 
            {
                return true;
            }
        }
        return false;
    }


    Array.prototype.add = function(key, value) 
    {
        if(this.contains(key))
            this[key] = value;
        else
        {
            this.push(key);
            this[key] = value;
        }
    }


    Array.prototype.remove = function(key) 
    {
        for(var i = 0; i < this.length; ++i)
        {
            if(this[i] == key)
            {
                this.splice(i, 1);
                return;
            }
        }
    }



    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }

        return vars;
    }



    function ForwardAndHideVariables() {
        var dictParameters = getUrlVars();

        dictParameters.add("mno", "pqr");
        dictParameters.add("mno", "stfu");

        dictParameters.remove("mno");



        for(var i = 0; i < dictParameters.length; i++)
        {
            var key = dictParameters[i];
            var value = dictParameters[key];
            alert(key + "=" + value);
        }
        // And now forward with HTTP-POST
        aa_post_to_url("Default.aspx", dictParameters);
    }


    function aa_post_to_url(path, params, method) {
        method = method || "post";

        var form = document.createElement("form");

        //move the submit function to another variable
        //so that it doesn't get written over if a parameter name is 'submit'
        form._submit_function_ = form.submit;

        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var i = 0; i < params.length; i++)
        {
            var key = params[i];

            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }

        document.body.appendChild(form);
        form._submit_function_(); //call the renamed function
    }

다른 답변이 지적했듯이, 당신이 사용하고있는 것은 JavaScript 배열이 아니라 JavaScript 객체로, 모든 키가 문자열로 변환 된 것을 제외하고는 다른 언어의 연관 배열처럼 작동합니다. 새로운 지도 키를 원래 유형으로 저장합니다.

객체가 아닌 배열이 있으면 배열을 사용할 수 있습니다. .필터 기능, 제거하려는 항목없이 새 배열을 반환하려면 다음과 같습니다.

var myArray = ['Bob', 'Smith', 25];
myArray = myArray.filter(function(item) {
    return item !== 'Smith';
});

오래된 브라우저와 jQuery가있는 경우 jQuery는 다음과 같습니다. $.grep 방법 비슷하게 작동합니다.

myArray = $.grep(myArray, function(item) {
    return item !== 'Smith';
});

에어 비앤비 스타일 가이드에는이를 수행하는 우아한 방법이 있습니다 (ES7).

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }

저작권: https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90

어떤 이유로 든 삭제 키가 작동하지 않는 경우 (나에게 작동하지 않는 것처럼)

당신은 그것을 분류 한 다음 정의되지 않은 값을 필터링 할 수 있습니다.

// to cut out one element via arr.splice(indexToRemove, numberToRemove);
array.splice(key, 1)
array.filter(function(n){return n});

스플 라이스 리턴이 제거 된 요소를 반환하기 때문에 그들을 시도하고 체인하지 마십시오.

'정의되지 않은'에 명시 적으로 할당하여지도에서 항목을 제거 할 수 있습니다. 귀하의 경우와 같이 :

myArray [ "lastName"] = 정의되지 않은;

당신이 있다면 그것은 매우 간단합니다 aUNDSCORE.JS 프로젝트의 종속성 -

_.omit(myArray, "lastname")

우리는 그것을 함수로 사용할 수 있습니다. 각도는 프로토 타입으로 사용하는 경우 약간의 오류를 던집니다. 감사합니다 @harpywar. 문제를 해결하는 데 도움이되었습니다.

var removeItem = function (object, key, value) {
    if (value == undefined)
        return;

    for (var i in object) {
        if (object[i][key] == value) {
            object.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

removeItem(collection, "id", "87353080-8f49-46b9-9281-162a41ddb8df");

사용함으로써 "delete" 키워드는 JavaScript의 배열에서 배열 요소를 삭제합니다.

예를 들어,

다음 진술을 고려하십시오.

var arrayElementToDelete = new Object();

arrayElementToDelete["id"]           = "XERTYB00G1"; 
arrayElementToDelete["first_name"]   = "Employee_one";
arrayElementToDelete["status"]       = "Active"; 

delete arrayElementToDelete["status"];

코드의 마지막 줄은 배열에서 "상태"인 배열 요소를 제거합니다.

var myArray = newmyArray = new Object(); 
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;

var s = JSON.stringify(myArray);

s.replace(/"lastname[^,}]+,/g,'');
newmyArray = JSON.parse(p);

루핑/반복없이 우리는 동일한 결과를 얻습니다

"배열"의 경우 :

색인을 알고 있다면 :

array.splice(index, 1);

가치를 알고 있다면 :

function removeItem(array, value) {
    var index = array.indexOf(value);
    if (index > -1) {
        array.splice(index, 1);
    }
    return array;
}

가장 큰 대답 delete 객체의 경우에는 잘 작동하지만 실제 배열에는 적합하지 않습니다. 내가 사용하는 경우 delete 루프에서 요소를 제거하지만 요소를 다음과 같이 유지합니다. empty 그리고 배열의 길이는 변하지 않습니다. 이것은 일부 시나리오에서 문제가 될 수 있습니다.

예를 들어, 제거 후 MyArray에서 myArray.toString ()을 수행하는 경우 delete 빈 항목을 만듭니다.

나에게 유일한 작업 방법 :

function removeItem (array, value) {
    var i = 0;
    while (i < array.length) {
        if(array[i] === value) {
            array.splice(i, 1);
        } else {
            ++i;
        }
    }
    return array;
}

용법:

var new = removeItem( ["apple","banana", "orange"],  "apple");
// ---> ["banana", "orange"]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top