最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to parse null from "null" string value - Stack Overflow

programmeradmin3浏览0评论
var hello = 'null';

How do I remove the quotes so var hello will truly equal null (and not a string)? I'm curious on how to do this without using JSON.parse.

var hello = 'null';

How do I remove the quotes so var hello will truly equal null (and not a string)? I'm curious on how to do this without using JSON.parse.

Share Improve this question edited Jun 30, 2018 at 1:49 Aman Chhabra 3,8941 gold badge25 silver badges39 bronze badges asked Jun 30, 2018 at 1:26 dlearnsdlearns 711 gold badge1 silver badge7 bronze badges 12
  • 1 You don't. You test your value, and assign accordingly. A counter-question would be "what do you think you would concretely use this for?" because it's a good bet that what you're trying to do has a better way to do it. – Mike 'Pomax' Kamermans Commented Jun 30, 2018 at 1:28
  • Type in var hello = null;? Or do something like: var hello = 'null'; var bar = hello === 'null' ? null : hello;? – user2864740 Commented Jun 30, 2018 at 1:29
  • 1 'null' is a string. It doesn't have any quotes, you can't remove them. How did you get this value? Further, what's wrong with JSON.parse? – Adam Jenkins Commented Jun 30, 2018 at 1:29
  • The delete key? – Sean F Commented Jun 30, 2018 at 1:30
  • 1 There is something really wrong with your JSON. The stringify JSON should look something like this '{"someObj":null}' and not '{"someObj":"null"}' – Aman Chhabra Commented Jun 30, 2018 at 1:40
 |  Show 7 more ments

3 Answers 3

Reset to default 3

Without JSON.parse, you cannot.

You can evaluate hello and alter its value later on in the code, which is much more real-world scenario.

hello = hello === 'null' ? null : hello

Assign null, I've just done this:

var a=1;
console.log(a);
a=null;
console.log(a);
console.log(a===null);

Results:

1
null
true

Though, null in JS is also a value.

You could eval or parse it from JSON (but eval is a terrible approach, I only mention it for the sake of this specific example). Like,

var hello = JSON.parse('null');
console.log(hello === null);

发布评论

评论列表(0)

  1. 暂无评论