JavaScript基础

打印

When we write console.log() what we put inside the parentheses will get printed, or logged, to the console.

console.log(100);

注释

single line comment will comment out a single line and is denoted with two forward slashes // preceding it.    

// Prints 5 to the console
console.log(5);

multi-line comment will comment out multiple lines and is denoted with /* to begin the comment, and */ to end the comment.    

/*
This is all commented 
console.log(10);
None of this is going to run!
console.log(99);
*/

You can also use this syntax to comment something out in the middle of a line of code:

console.log(/*IGNORED!*/ 5);  // Still just prints 5 

Data Types

  • Number: Any number, including numbers with decimals: 48151623.42.
  • String: Any grouping of characters on your keyboard (letters, numbers, spaces, symbols, etc.) surrounded by single quotes: ' ... ' or double quotes " ... ", though we prefer single quotes. Some people like to think of string as a fancy word for text.
  • Boolean: This data type only has two possible values— either true or false (without quotes). It’s helpful to think of booleans as on and off switches or as the answers to a “yes” or “no” question.
  • Null: This data type represents the intentional absence of a value, and is represented by the keyword null (without quotes).
  • Undefined: This data type is denoted by the keyword undefined (without quotes). It also represents the absence of a value though it has a different use than nullundefined means that a given value does not exist.
  • Symbol: A newer feature to the language, symbols are unique identifiers, useful in more complex coding. No need to worry about these for now.
  • Object: Collections of related data.

The first 6 of those types are considered primitive data types. They are the most basic data types in the language.

Arithmetic Operators and String Concatenation

  1. Add: +
  2. Subtract: -
  3. Multiply: *
  4. Divide: /
  5. Remainder: %
Add: +
Subtract: -
Multiply: *
Divide: /
Remainder: %
console.log('hi' + 'ya'); // Prints 'hiya'
console.log('wo' + 'ah'); // Prints 'woah'
console.log('I love to ' + 'code.')
// Prints 'I love to code.'

Properties

console.log('Hello'.length); // Prints 5

和java不同,这里的length是hello这个string的属性,java里string要调用length方法返回值

Review

  • Data is printed, or logged, to the console, a panel that displays messages, with console.log().
  • We can write single-line comments with // and multi-line comments between /* and */.
  • There are 7 fundamental data types in JavaScript: strings, numbers, booleans, null, undefined, symbol, and object.
  • Numbers are any number without quotes: 23.8879
  • Strings are characters wrapped in single or double quotes: 'Sample String'
  • The built-in arithmetic operators include +-*/, and %.
  • Objects, including instances of data types, can have properties, stored information. The properties are denoted with a . after the name of the object, for example: 'Hello'.length.
  • Objects, including instances of data types, can have methods which perform actions. Methods are called by appending the object or instance with a period, the method name, and parentheses. For example: 'hello'.toUpperCase().
  • We can access properties and methods by using the ., dot operator.
  • Built-in objects, including Math, are collections of methods and properties that JavaScript provides.

变量 var

var myName = 'Arya';
console.log(myName);
// Output: Arya
  • Variable names cannot start with numbers.
  • Variable names are case sensitive, so myName and myname would be different variables. It is bad practice to create two variables that have the same name using different cases.
  • Variable names cannot be the same as keywords.

变量 let

let meal = 'Enchiladas';
console.log(meal); // Output: Enchiladas
meal = 'Burrito';
console.log(meal); // Output: Burrito
  • If we don’t assign a value to a variable declared using the let keyword, it automatically has a value of undefined.
  • We can reassign the value of the variable.

String Interpolation格式化输出

const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);
// Output: I own a pet armadillo.
  • a template literal is wrapped by backticks ` (this key is usually located on the top of your keyboard, left of the 1 key).
  • Inside the template literal, you’ll see a placeholder${myPet}. The value of myPet is inserted into the template literal.
  • When we interpolate `I own a pet ${myPet}.`, the output we print is the string: 'I own a pet armadillo.'

typeof operator

const unknown1 = 'foo';
console.log(typeof unknown1); // Output: string
 
const unknown2 = 10;
console.log(typeof unknown2); // Output: number
 
const unknown3 = true; 
console.log(typeof unknown3); // Output: boolean

if

if (false) {
  console.log('The code in this block will not run.');
} else {
  console.log('But the code in this block will!');
}
 

Comparison Operators

  • Is equal to: ===
  • Is not equal to: !==

一些特殊情况的bolean值

let myVariable = 'I Exist!';
 
if (myVariable) {
   console.log(myVariable)
} else {
   console.log('The variable does not exist.')
}

语句中的代码块将运行,这种情况下我们认为myVarialble为真值。

So which values are falsy— or evaluate to false when checked as a condition? The list of falsy values includes:

  • 0
  • Empty strings like "" or ''
  • null which represent when there is no value at all
  • undefined which represent when a declared variable lacks a value
  • NaN, or Not a Number  

Truthy and Falsy Assignment特殊的赋值方法

假设您有一个网站,想用用户的用户名制作个性化的问候语。有时,用户没有账户,因此用户名变量是虚假的。下面的代码会检查用户名是否已定义,如果未定义,则分配一个默认字符串:

let username = '';
let defaultName;
 
if (username) {
  defaultName = username;
} else {
  defaultName = 'Stranger';
}
 
console.log(defaultName); // Prints: Stranger

我们可以简写为这样:

let username = '';
let defaultName = username || 'Stranger';
 
console.log(defaultName); // Prints: Stranger

Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if it is truthy, and it will be assigned the value of 'Stranger' if username is falsy. This concept is also referred to as short-circuit evaluation.

Ternary Operator 三元表达式

let isNightTime = true;
 
if (isNightTime) {
  console.log('Turn on the lights!');
} else {
  console.log('Turn off the lights!');
}

==

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');

The switch keyword

let groceryItem = 'papaya';
 
switch (groceryItem) {
  case 'tomato':
    console.log('Tomatoes are $0.49');
    break;
  case 'lime':
    console.log('Limes are $1.49');
    break;
  case 'papaya':
    console.log('Papayas are $1.29');
    break;
  default:
    console.log('Invalid item');
    break;
}
 
// Prints 'Papayas are $1.29'

review

  • An if statement checks a condition and will execute a task if that condition evaluates to true.
  • if...else statements make binary decisions and execute different code blocks based on a provided condition.
  • We can add more conditions using else if statements.
  • Comparison operators, including <><=>====, and !== can compare two values.
  • The logical and operator, &&, or “and”, checks if both provided expressions are truthy.
  • The logical operator ||, or “or”, checks if either provided expression is truthy.
  • The bang operator, !, switches the truthiness and falsiness of a value.
  • The ternary operator is shorthand to simplify concise if...else statements.
  • A switch statement can be used to simplify the process of writing multiple else if statements. The break keyword stops the remaining cases from being checked and executed in a switch statement.

你可能感兴趣的:(javascript,前端,开发语言)