简体   繁体   中英

I can't seem to understand the meaning of this one line of code (JavaScript)

I've read a bunch of tutorials and posts but I just got more and more confused. In Laymen's terms(extremely simple and explicit terms), what does the code below do?? what is replace(/ /g, '-') ? what is req.params.item?

return todo.item.replace(/ /g, '-') !== req.params.item;

And for more context, the entire code is shown below.

var bodyParser = require('body-parser');
var data = [{item: 'get milk'}, {item: 'walk dog'}, {item: 'kick 
some coding ass'}];
var urlencodedParser = bodyParser.urlencoded({extended: false});

module.exports = function(app) {

app.get('/todo', function(req, res){
    res.render('todo', {todos: data});

});


app.post('/todo', urlencodedParser, function(req, res){
    data.push(req.body);
    res.json(data);
});


app.delete('/todo/:item', function(req, res){
    data = data.filter(function(todo){
        return todo.item.replace(/ /g, '-') !== req.params.item;
    });
    res.json(data);
});

};

It turns all spaces in the todo.item string into dashes, compares the replaced string to req.params.item , and returns true if they are different. For example, if todo.item is foo bar , and req.params.item is foo-bar , it will return false .

What the filter does

data = data.filter(function(todo){
    return todo.item.replace(/ /g, '-') !== req.params.item;
});

is it turns data into an array which contains only items which do not pass that test.

 let data = [ { item: 'foo bar' }, { item: 'bar baz' }, { item: 'baz buzz' }, ]; const req = { params: { item: 'bar-baz' }}; data = data.filter(function(todo){ return todo.item.replace(/ /g, '-') !== req.params.item; }); console.log(data); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM